package net.yvesd.cellhunter;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import net.yvesd.cellhunter.model.coverage.SignalStrengthLocation;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.OverlayItem;

public class CellItemizedOverlay extends ItemizedOverlay<OverlayItem> {

	private List<SignalStrengthLocation> mLocations = new ArrayList<SignalStrengthLocation>();
	private Resources resources;

	public CellItemizedOverlay(Drawable defaultMarker, Resources r) {
		super(boundCenter(defaultMarker));
		this.resources = r;
	}

	@Override
	protected OverlayItem createItem(int i) {
		final SignalStrengthLocation loc = mLocations.get(i);

		GeoPoint geo = new GeoPoint(
				(int) (loc.getLocation().getLatitude() * 1000000), (int) (loc
						.getLocation().getLongitude() * 1000000));

		return new OverlayItem(geo, "", "") {
			@Override
			public Drawable getMarker(int stateBitset) {
				GradientDrawable s = (GradientDrawable) resources
						.getDrawable(R.drawable.cell);

				int color = getColor(loc.getSignalStrengh());
				s.setColor(color);

				return boundCenter(s);
			}

			private int getColor(int signalStrength) {
				// FIXME PIGGY
				if (signalStrength == 99)
					return Color.rgb(128, 128, 128);

				if (signalStrength <= 15) {
					int g = 17 * signalStrength;
					return Color.rgb(255, g, 0);
				} else {
					int r = 255 - (17 * (signalStrength - 16));
					return Color.rgb(r, 255, 0);
				}
			}
		};
	}

	/**
	 * Receive new locations
	 * 
	 * @param newLocaions
	 *            The new locations to use
	 */
	public void updateMap(Set<SignalStrengthLocation> newLocations) {

		mLocations = new ArrayList<SignalStrengthLocation>();
		for (SignalStrengthLocation signalStrenghLocation : newLocations) {
			mLocations.add(signalStrenghLocation);
		}

		populate();
	}

	@Override
	public int size() {
		return mLocations.size();
	}
}
